package com.jackson.service.impl;

/*
 * Author: JacksonCoder
 * FileName: RabbitMqServiceImpl
 * Version: 1.0.0
 * Date: 2024/12/12
 */

import com.jackson.config.RabbitMQConfig;
import com.jackson.service.RabbitMqService;
import com.rabbitmq.client.Channel;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.handler.annotation.Header;
import org.springframework.stereotype.Service;

import java.io.IOException;

@Service("rabbitmqService")
public class RabbitMqServiceImpl implements RabbitMqService {

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Override
    @RabbitListener(queues = {RabbitMQConfig.DIRECT_QUEUE})
    public void receiveMessage(String message, Channel channel, @Header(AmqpHeaders.DELIVERY_TAG) long deliveryTag) {
//        String message = (String) amqpTemplate.receiveAndConvert(RabbitMQConfig.DIRECT_QUEUE);
        try {
            System.out.println("接收到的mq消息：" + message);
            // 处理业务
            System.out.println("处理业务！！！");
            System.out.println("deliveryTag= " + deliveryTag);
            // long deliveryTag, boolean multiple
            if (deliveryTag == 5) {
                channel.basicAck(deliveryTag, true);
            }
        } catch (Exception e) {
            e.printStackTrace();
            // 拒绝签收
            try {
                channel.basicNack(deliveryTag, false, true);
                Thread.sleep(1000);
            } catch (IOException e1) {
                e1.printStackTrace();
            } catch (InterruptedException ex) {
                throw new RuntimeException(ex);
            }

        }

    }

    @Override
    @RabbitListener(queues = {RabbitMQConfig.DIRECT_QUEUE})
    public void receiveMessage2(String message) {
//        System.out.println("接受者1: 接收到的mq消息：" + message);
//        System.out.println(1/0);  // 测试异常处理
        System.out.println("队列1接收日志消息： " + message);
    }

    @Override
    @RabbitListener(queues = {RabbitMQConfig.DIRECT_QUEUE})
    public void receiveMessage3(String message) {
//        System.out.println("接受者2: 接收到的mq消息：" + message);
//        System.out.println(1/0);  // 测试异常处理
        System.out.println("队列2接收日志消息： " + message);
    }

    @Override
    @RabbitListener(queues = {RabbitMQConfig.SUB_QUEUE1})
    public void receiveSubMessage1(String message) {
        System.out.println("订阅者1：接收到的mq消息：" + message);
    }

    @Override
    @RabbitListener(queues = {RabbitMQConfig.SUB_QUEUE2})
    public void receiveSubMessage2(String message) {
        System.out.println("订阅者2：接收到的mq消息：" + message);
    }

}
